package com.lucky.common.init;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lucky.common.cache.RightCache;
import com.lucky.common.mapper.RoleMapper;
import com.lucky.common.pojo.po.RolePO;
import com.lucky.common.pojo.vo.PermVO;
import com.lucky.common.service.PermService;
import com.lucky.common.util.TreeUtil;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class InitRight implements ApplicationRunner {
	
    @Resource
    ServletContext application;

    @Resource
	PermService permService;

	@Resource
	private com.lucky.common.mapper.PermMapper permMapper;

	@Resource
	private RoleMapper roleMapper;
	
	@Resource
	RightCache rightCache;

	@Override
    public void run(ApplicationArguments args) throws Exception {

    	try {
			log.info("init PrivilegeVO cache begin!");

			rightCache.roleList = roleMapper.selectList(Wrappers.emptyWrapper());
			for(RolePO r : rightCache.roleList) {
				List<String> lUrl = permService.queryRightUrlByRole(r.getRoleCode());
				rightCache.roleUrlMap.put(r.getRoleCode(), lUrl);

				List<PermVO> lRight = permService.queryRightByRole(r.getRoleCode());
				rightCache.roleRightMap.put(r.getRoleCode(), lRight);

				List<PermVO> tree = TreeUtil.makeTree(lRight, p->Objects.equals(p.getSupRightCodeId(), 0L), (p, c)-> Objects.equals(p.getId(), c.getSupRightCodeId()), PermVO::setChildList);
				rightCache.roleTreeMap.put(r.getRoleCode(), tree);
			}
			log.info("init PrivilegeVO cache finish!");

		} catch (Exception e) {
			log.error("init PrivilegeVO cache error!",e);
		}
        
    }

    
}
